package MTClient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import MTClient.MTConstant;
import MTRequest.MTClientCreateEvent;
import MTRequest.MTClientSynContactList;
import MTRequest.MTClientSynDataFromLocalDB;
import MTRequest.MTClientSynDataFromServerDB;
import MTRequest.MTRequest;
import MTRequest.MTRequestDataSource;
import MTRequest.MTClientRegisterRequest;
import MTRequest.MTRequestFactory;

/**
 * Message Center manage the Output and Input Stream of the connected socket.
 * It receive MSG from a peer and pass the raw data to a MTRequest class to handle 
 * the request.
 * 
 * @author King
 *
 */
public class MessageCentre {
	
	private DataOutputStream mOutput = null;
	private DataInputStream mInput = null;
	private MTRequest mRequest = null;
	
	public MessageCentre( DataInputStream aInput, DataOutputStream aOutput )
	{
		this.mOutput = aOutput;
		this.mInput = aInput;
		
	}
	
	public MTRequest GetRequest()
	{
		return mRequest;
	}
	
	public void ReceiveMSG() throws IOException
	{
		//Over and over, forever ...
		while (true) {
			//... read the next message ...
			String message = mInput.readUTF();
			//... tell the world ...
			System.out.println( "Client Receive: "+message );
			
			int requestID = ProtocolHeaderGetRequestID( message );
			HandleCreateRequest( requestID );
			mRequest.ProcessMSG( message );
		}
	}
	
	public void SendMSG( String message )
	{
		try {
			System.out.println( "Client Send Request:" + message );
			mOutput.writeUTF( message );
		} 
		catch( IOException ie ) { 
			System.out.println( ie ); 
			
			// May handle disconnection;
		}
	}
	
	public void SendRequest( int aRequestID, MTRequestDataSource aRequestDataSource )
	{
		HandleCreateRequest( aRequestID );
		mRequest.SetRequestDataSource( aRequestDataSource );
		mRequest.SendRequest();
	}
	
	public void HandleCreateRequest( int aRequestID )
	{
		if( null == mRequest ){
			mRequest = MTRequestFactory.CreateRequest( aRequestID, this );
		}
	}
	
	private int ProtocolHeaderGetRequestID( String protocol )
	{
		// Get Request ID
		String [] strings = protocol.split("" + MTConstant.MT_REQ_ITEM_SEPARATER );
		for( int i = 0; i < strings.length; ++i ){
			System.out.println( "Protocol Content " + i + ":" + strings[i]);
		}
		return Integer.valueOf( strings[0] );
	}
	
	public void FinishRequest()
	{
		mRequest = null;
	}

}
